/*
	This file is part of BGO External Jukebox.

	BGO External Jukebox is free software:
	you can redistribute it and/or modify it under the terms
	of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License,
	or (at your option) any later version.

	BGO External Jukebox is distributed  in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
	or FITNESS FOR A PARTICULAR PURPOSE.

	See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License  along with
	BGO External Jukebox. If not, see <http://www.gnu.org/licenses/>.
*/

function defaultSetting(settingName, defaultValue)
{
	if (typeof(localStorage[settingName]) === 'undefined')
	{
		localStorage[settingName] = defaultValue;
	}
}

defaultSetting('_bgo_detach_jukebox', 1);

var jukeboxTab = undefined;

chrome.tabs.onRemoved.addListener(
	function(tabID)
	{
		if (jukeboxTab == tabID)
		{
			jukeboxTab = undefined;
		}
	}
);

chrome.extension.onMessage.addListener(
	function (request, sender, sendResponse)
	{
		if (request.jukebox)
		{
			var url = 'https://www.youtube.com/watch?v=' + request.jukebox;

			if (typeof(jukeboxTab) !== 'undefined')
			{
				chrome.tabs.get(jukeboxTab,
					function(tab)
					{
						if (typeof(tab) !== 'undefined')
						{
							if (tab.url != url)
							{
								chrome.tabs.update(jukeboxTab, {url: url});
								chrome.tabs.executeScript(jukeboxTab, {code: 'window.onload=function() {document.title = "♫:" + document.title;};'});
							}
						}
						else
						{
							jukeboxTab = undefined;
						}
					}
				);
			}

			if (typeof(jukeboxTab) === 'undefined')
			{
				chrome.tabs.create(
					{
						url: url,
						active: false
					},
					function(tab)
					{
						if (typeof(tab) !== 'undefined')
						{
							jukeboxTab = tab.id;
							chrome.tabs.executeScript(jukeboxTab, {code: 'window.onload=function() {document.title = "♫:" + document.title;};'});
						}
						else
						{
							jukeboxTab = undefined;
						}
					}
				);
			}
		}
		else if (request.close == true)
		{
			if (typeof(jukeboxTab) !== 'undefined')
			{
				chrome.tabs.remove(jukeboxTab);
			}
		}
		else if (request.settings == true)
		{
			settings = localStorage;
			sendResponse(settings);
		}
	}
);
